package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.heima.apis.user.IUserClient;
import com.heima.comment.pojos.ApArticleCommentLike;
import com.heima.comment.service.ApArticleCommentService;
import com.heima.comment.service.CommentAutoScanService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.comment.dtos.ArticleSaveDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentPageDto;
import com.heima.comment.pojos.ApArticleComment;
import com.heima.model.comment.vos.PageCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
@Transactional
public class ApArticleCommentServiceImpl implements ApArticleCommentService {

    @Autowired
    private CommentAutoScanService commentAutoScanService;


    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IUserClient IUserClient;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;


    //发布评论
    @Override
    public ResponseResult saveComment(ArticleSaveDto dto) {
        ApUser user = ApUserThreadLocalUtil.getUser();
        if (user == null || dto == null || dto.getContent() == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (dto.getContent().length() > 140) {
            throw new RuntimeException("评论字数超额");
        }

        //获取用户
        ApUser user1 = IUserClient.findUserById(user.getId());

        ApArticleComment apArticleComment = new ApArticleComment();
        apArticleComment.setContent(dto.getContent());
        apArticleComment.setAuthorId(user.getId());
        apArticleComment.setAuthorName(user1.getName());
        apArticleComment.setCreatedTime(new Date());
        apArticleComment.setFlag(0);
        apArticleComment.setType(0);
        apArticleComment.setFlag(0);
        apArticleComment.setLikes(0);
        apArticleComment.setReply(0);
        apArticleComment.setEntryId(dto.getArticleId());
        mongoTemplate.save(apArticleComment);


        //审核评论
        boolean autoScan = commentAutoScanService.autoScan(apArticleComment.getId());
        if (!autoScan) {
            throw new RuntimeException("评论不合格");
        }

        //远程评论+1
        kafkaTemplate.send(ArticleConstants.ARTICLE_ADD_COMMENT_TOPIC, JSONObject.toJSONString(apArticleComment.getEntryId()));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    //分页查询
    @Override
    public ResponseResult<CommentPageDto> load(CommentPageDto pageDto) {

        ApUser user = ApUserThreadLocalUtil.getUser();

        //检验参数
        if (pageDto == null || pageDto.getArticleId() == null || user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        //处理参数
        pageDto.setSize(10);


       // Query query = Query.query(Criteria.where("entryId").is(pageDto.getArticleId()).and("createdTime").lt(pageDto.getMinDate())).with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(pageDto.getSize());
        Query query = Query.query(Criteria.where("entryId").is(pageDto.getArticleId()).and("createdTime").lt(pageDto.getMinDate()));
        query.with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(pageDto.getSize());
        List<ApArticleComment> apArticleComments = mongoTemplate.find(query, ApArticleComment.class);


        List<String> idList = apArticleComments.stream().map(ApArticleComment::getId).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentId").in(idList).and("authorId").is(user.getId()));
        List<ApArticleCommentLike> apCommentLikes = mongoTemplate.find(query1, ApArticleCommentLike.class);
        if (apCommentLikes.isEmpty()) {
            return ResponseResult.okResult(apArticleComments);
        }

        List<PageCommentVo> list = new ArrayList<>();
        for (ApArticleComment apArticleComment : apArticleComments) {
            PageCommentVo pageCommentVo = new PageCommentVo();
            BeanUtils.copyProperties(apArticleComment, pageCommentVo);
            for (ApArticleCommentLike apCommentLike : apCommentLikes) {
                if (apArticleComment.getId().equals(apCommentLike.getCommentId())) {
                    pageCommentVo.setOperation("0");
                }
            }
            list.add(pageCommentVo);
        }
        return ResponseResult.okResult(list);
    }

    //评论点赞
    @Override
    public ResponseResult like(CommentLikeDto dto) {

        Query query = Query.query(Criteria.where("_id").is(dto.getCommentId()));
        ApArticleComment apArticleComment = mongoTemplate.findOne(query, ApArticleComment.class);

        //点赞
        if (dto.getOperation() == 0) {
            apArticleComment.setLikes(apArticleComment.getLikes() + 1);
            mongoTemplate.save(apArticleComment);

            ApArticleCommentLike apArticleCommentLike = new ApArticleCommentLike();
            apArticleCommentLike.setAuthorId(apArticleComment.getAuthorId());
            apArticleCommentLike.setCommentId(dto.getCommentId());
            mongoTemplate.save(apArticleCommentLike);



        } else if(dto.getOperation() == 1){
            //取消点赞
            apArticleComment.setLikes(apArticleComment.getLikes() - 1);
            mongoTemplate.save(apArticleComment);
            Query query1 = Query.query(Criteria.where("_id").is(apArticleComment.getAuthorId()));
            ApArticleCommentLike apArticleCommentLike = mongoTemplate.findOne(query1, ApArticleCommentLike.class);
            if (apArticleCommentLike != null) {
                mongoTemplate.remove(apArticleCommentLike);
            }

        }

        Map<String, Integer> map = new HashMap<>();
        map.put("likes",apArticleComment.getLikes());
        return ResponseResult.okResult(map);
    }
}